<!--
 * @Author: H_x
 * @Date: 2024-09-13 11:21:10
 * @LastEditTime: 2024-09-13 17:29:10
 * @LastEditors: H_x
 * @Description: 
 * @FilePath: /browser_captcha_identify/src/view/components/urlForm.vue
-->
<template>
    <el-form ref="updateFormRef" :rules="rules" :label-position="'left'" label-width="100px" :model="curForm">
        <el-form-item prop="url" label="链接地址">
            <el-input v-model="curForm.url" placeholder="全部可以用'*'" />
        </el-form-item>
        <el-form-item prop="captchaPath" label="验证码定位">
            <el-input v-model="curForm.captchaPath" />
            <el-tag @click="selectEle(curForm, 'captchaPath')">选择元素</el-tag>
        </el-form-item>
        <el-form-item prop="inputPath" label="输入框定位">
            <el-input v-model="curForm.inputPath" />
            <el-tag @click="selectEle(curForm, 'inputPath')">选择元素</el-tag>
        </el-form-item>
        <el-form-item prop="buttonPath" label="按钮定位">
            <el-input v-model="curForm.buttonPath" />
            <el-tag @click="selectEle(curForm, 'buttonPath')">选择元素</el-tag>
        </el-form-item>
        <div style="margin:10px">
            <el-button type="primary" round @click="updateConfirm">确定</el-button>
            <el-button type="default" round @click="emits('cancel')">取消</el-button>
        </div>
    </el-form>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch } from "vue";

const props = defineProps({
    form: {
        type: Object,
        default: () => ({})
    }
})

const emits = defineEmits(['confirm', 'cancel'])

const updateFormRef = ref()
const rules = ref([])
const curForm = ref({
    url: '',
    captchaPath: '',
    inputPath: '',
    buttonPath: ''
})
const formKey = ref("");
watch(
    () => props.form,
    (newVal) => {
        curForm.value = newVal
    },
    { immediate: true, deep: true }
)
const selectEle = async (curForm, key) => {
    formKey.value = key;
    // chrome.runtime.sendMessage({
    //     command: 'setPopupShow',
    //     parameter: {
    //         status: false
    //     }
    // });
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    chrome.scripting.executeScript({
        target: { tabId: tab.id },
        function: async (key) => {
            const getXPath = (element) => {
                if (element.id !== '') {
                    return '//*[@id="' + element.id + '"]';
                }

                if (element === document.body) {
                    return '/html/body';
                }

                let ix = 0;
                let siblings = element.parentNode.childNodes;
                for (let i = 0; i < siblings.length; i++) {
                    let sibling = siblings[i];
                    if (sibling === element) {
                        let xpath = getXPath(element.parentNode) + '/';
                        switch (element.tagName) {
                            case 'INPUT':
                                if (element.type && element.type !== 'text') {
                                    xpath += element.tagName + '[@type="' + element.type + '"]';
                                } else {
                                    xpath += element.tagName;
                                }
                                break;
                            default:
                                xpath += element.tagName;
                                break;
                        }
                        if (ix > 0) {
                            xpath += '[' + (ix + 1) + ']';
                        }
                        return xpath;
                    } else if (sibling.nodeType === 1 && sibling.tagName === element.tagName) {
                        ix++;
                    }
                }
            }
            return await new Promise((resolve, reject) => {
                let dict = {
                    captchaPath: "img",
                    inputPath: "input",
                    buttonPath: "button",
                };
                const allowElements = [...document.querySelectorAll(dict['captchaPath'])];
                let mouseoverHandler = (event) => {
                    event.target.style.border = "1px dashed #000";
                    event.target.addEventListener("mouseout", mouseoutHandler);
                };
                let mouseoutHandler = (event) => {
                    event.target.style.border = "none";
                };
                allowElements.forEach((ele) => {
                    let clickHandler = (event) => {
                        allowElements.forEach((i) => {
                            i.style.border = "none";
                            i.removeEventListener("mouseover", mouseoverHandler);
                            i.removeEventListener("mouseout", mouseoutHandler);
                            i.removeEventListener("click", clickHandler);
                        });
                        let xpath = getXPath(event.target);
                        console.log(xpath, 'xpath');

                        resolve(xpath);
                    };
                    ele.addEventListener("mouseover", mouseoverHandler);
                    ele.addEventListener("click", clickHandler);
                });
            });
        }
    }).then(res => {
        if (res && res.length > 0) {
            chrome.runtime.sendMessage({
                command: 'setPopupShow',
                parameter: {
                    status: true
                }
            });
            curForm[formKey.value] = res[0].result;
        }
    })
};
const updateConfirm = async () => {
    await updateFormRef.value.validate((valid, fields) => {
        if (valid) {
            emits('confirm', curForm.value);
        } else {
            console.log("error submit!", fields);
        }
    });
}

</script>
